package com.ghsc.ghxc.jsb.ui.message.activity

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.event.RxBus
import com.cn.appcore.event.RxBusBean
import com.cn.appcore.event.SchedulerTransformer
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.showToast
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.widget.CustomRefreshListener
import com.cn.appcore.widget.RefreshHelper
import com.flyco.roundview.RoundTextView
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.CustSignKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.config.UserManager
import com.ghsc.ghxc.jsb.databinding.ActivityFriendsListBinding
import com.ghsc.ghxc.jsb.ui.message.bean.ChatDataResultBean
import com.ghsc.ghxc.jsb.ui.message.view.RouterUtils
import com.ghsc.ghxc.jsb.view.ConfirmCancelPopViiew
import com.ghsc.ghxc.jsb.view.NotDataView
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.netease.nimlib.sdk.NIMClient
import com.netease.nimlib.sdk.friend.FriendService
import com.netease.nimlib.sdk.msg.SystemMessageService
import com.netease.nimlib.sdk.msg.constant.SystemMessageType
import com.scwang.smart.refresh.layout.api.RefreshLayout

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.message.activity
 * 类名：FriendsListActivity
 * 创建时间：2024/5/7 17:01
 * 创建人 @author： xiaolin
 * 描述 ：Todo...我的好友
 */
class FriendsListActivity : BaseVMActivity<MessageViewModel, ActivityFriendsListBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_friends_list
    }

    override fun attachVMClass(): Class<MessageViewModel>? {
        return MessageViewModel::class.java
    }


    private val mAdapter: FriendsListAdapter by lazy { FriendsListAdapter() }
    var mList = arrayListOf<ChatDataResultBean>()
    private var notDataView: View? = null
    var keyword:String=""
    var itemPosition =-1

    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }
    override fun initView() {
        UserManager.setImCount(0)
        binding.run {
            bar.topTitle.text="好友列表"
            bar.topLeftView.setOnClickListener { finish() }
        }
        binding.rvList.layoutManager = LinearLayoutManager(this)
        binding.rvList.adapter = mAdapter
        mAdapter.setNewInstance(mList)
        notDataView = NotDataView.notDataView(this, binding.rvList, binding.refreshLayout,"暂无数据")
        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (mAdapter.getItem(position).status==1){
                RouterUtils.startToJumpSingleChat(this,mAdapter.getItem(position).uid)
            }else{
                showToast("你们还不是好友喔...")
            }
        }

        mAdapter.setOnItemLongClickListener { adapter, view, position ->
            //长按事件
            XPopup.Builder(this)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                .asCustom(
                    ConfirmCancelPopViiew(
                        this, "提示", "确定要删除该好友吗？",
                        btnConfirm = {
                            itemPosition=position
                            val map: HashMap<String, Any> = HashMap()
                            map["fuid"] = mAdapter.getItem(position).uid
                            GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onDeleteFriendMethod(it1) }
                        },
                        btnCancel = {
                        },
                    )
                )
                .show()
            false
        }
        mAdapter.addChildClickViewIds(R.id.tvBtnNext)
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            //item里面某个按钮事件
            when(view.id){
                R.id.tvBtnNext ->{
                    val status = mAdapter.getItem(position).status
                    if(status==-1){
                        return@setOnItemChildClickListener
                    }
                    itemPosition=position
                    val map: HashMap<String, Any> = HashMap()
                    map["fuid"] = mAdapter.getItem(position).uid
                    map["ptype"] = 1
                    //1是同意
                    GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onActFriendMethod(it1) }
                }
            }
        }
        initRefreshLayout()
        pageNo = 1
        getListData()
        rxBusSubscription = RxBus.getDefault().toObservable(RxBusBean::class.java)
            .compose(SchedulerTransformer())
            .subscribe{ rxBusBean ->
                if (rxBusBean.id == CustSignKey.CHAT_EMPTY_NUM && rxBusBean.sign == CustSignKey.CHAT_EMPTY_NUM) {
                    pageNo = 1
                    getListData()
                }else if (rxBusBean.id == CustSignKey.CHAT_UNREAD_NUM && rxBusBean.sign == CustSignKey.CHAT_UNREAD_NUM) {
                    pageNo = 1
                    getListData()
                }
            }


        val types: MutableList<SystemMessageType> = ArrayList()
        types.add(SystemMessageType.AddFriend)
        // 将“添加好友”类型的系统通知标记为已读
        NIMClient.getService(SystemMessageService::class.java)
            .resetSystemMessageUnreadCountByType(types)
    }

    override fun initData() {
        super.initData()
        binding.run {
            tvBtnNext.setOnClickListener {
                if (TextUtils.isEmpty(binding.etSearch.text)){
                    showToast("请输入邀请码/手机号")
                }else{
                    keyword=binding.etSearch.text.toString()
                    pageNo = 1
                    getListData()
                }
            }
            etSearch.isFocusable = true
            etSearch.isFocusableInTouchMode = true
            etSearch.requestFocus()
            etSearch.setOnEditorActionListener(object : TextView.OnEditorActionListener {
                override fun onEditorAction(
                    v: TextView,
                    actionId: Int,
                    event: KeyEvent?
                ): Boolean {
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        // 先隐藏键盘
                        hideKeyboard(v)
                        keyword = binding.etSearch.text.toString().trim()
                        if (!TextUtils.isEmpty(keyword)) {
                            binding.etSearch.clearFocus()
                            hideKeyboard(binding.etSearch)
                            pageNo = 1
                            getListData()
                        }else{
                            keyword=""
                            pageNo = 1
                            getListData()
                        }
                        return true
                    }
                    return false
                }
            })
            etSearch.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }
                override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                }

                override fun afterTextChanged(p0: Editable?) {
                    if(TextUtils.isEmpty(p0.toString().trim())){
                        loge("搜索框没有内容触发")
                        keyword=""
                        pageNo = 1
                        getListData()
                    }
                }

            })

        }
    }

    private fun initRefreshLayout() {
        RefreshHelper.initRefreshLayout(binding.refreshLayout, object : CustomRefreshListener {
            override fun _onRefresh(refreshLayout: RefreshLayout?) {
                pageNo = 1
                getListData()
            }
            override fun _onLoadMore(refreshLayout: RefreshLayout?) {
                pageNo++
                getListData()
            }
        })
    }


    private fun getListData() {
        val map: HashMap<String, Any> = HashMap()
        map["pindex"] = pageNo
        map["psize"] = pageSize
        map["keyword"] = keyword
        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onFriendListMethod(it1) }
    }

    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@FriendsListActivity) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast(it)
            }
            againLoginMsg.observe(this@FriendsListActivity) {
                dismissLoading()
                binding.refreshLayout.finishRefresh()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }

            onActFriendData.observe(this@FriendsListActivity){
                //同意加好友
                showToast("操作成功")
                if (itemPosition>-1){
                    mAdapter.getItem(itemPosition).status=1
                }
                mAdapter.notifyItemChanged(itemPosition)
            }
            onDeleteFriendData.observe(this@FriendsListActivity){
                //删除好友
                if (itemPosition>-1){
                    mAdapter.removeAt(itemPosition)
                    RxBus.getDefault().post(
                        RxBusBean(CustSignKey.IM_DELETE_INFO, CustSignKey.IM_DELETE_INFO,mAdapter.getItem(itemPosition).uid)
                    )
                }
                mAdapter.notifyItemChanged(itemPosition)
            }
            onFriendListData.observe(this@FriendsListActivity) {
                //我的好友列表
                RefreshHelper.finishRefresh(binding.refreshLayout, pageNo)
                if (pageNo == 1) {
                    if (it.data.list.isNullOrEmpty()){
                        mAdapter.replaceData( it.data.list)
                        mAdapter.setEmptyView(notDataView!!)
                    } else {
                        mAdapter.replaceData( it.data.list)
                    }
                } else {
                    if (!it.data.list.isNullOrEmpty())
                        mAdapter.addData(it.data.list)
                }
            }

        }
    }


    class FriendsListAdapter   : BaseQuickAdapter<ChatDataResultBean, BaseViewHolder>(
        R.layout.friends_item) {

        override fun convert(helper: BaseViewHolder, item: ChatDataResultBean) {
            GlideUtil.ImageHeadLoad(this.context, item.headimg, helper.getView(R.id.userImgUrl))
            helper.setText(R.id.tvName, item.nickname)
            var textStatus = helper.getView<RoundTextView>(R.id.tvBtnNext)

            if(item.status!=1){
                textStatus.visibility = View.VISIBLE
                if(item.status==-1){
                    textStatus.delegate.backgroundColor=this.context.getCompatColor( R.color.btn_lvse)
                    if(TextUtils.isEmpty(item.statusch))
                        textStatus.text="同意"
                    else textStatus.text=item.statusch
                }else{
                    textStatus.delegate.backgroundColor=this.context.getCompatColor( R.color.app_main)
                    textStatus.text=item.statusch
                }
            }else{
                textStatus.visibility = View.GONE
            }
        }
    }
}